package com.zy.mc_module.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;

import androidx.annotation.NonNull;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.TextView;

import com.zy.mc_module.R;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * author : dq
 * date   : 19/4/13
 * desc   : 将字符串中的电话号码找出并设置点击事件
 */
public class SpannableStringUtil {
    /**
     * 将字符串中的电话号码设置点击事件和下划线
     *
     * @param tv
     * @param strTel
     */
    public static void setTelUrl(Context context, TextView tv, String strTel) {
        tv.setHighlightColor(Color.TRANSPARENT); //设置点击后的颜色为透明，否则会一直出现高亮
        tv.setText(setStrTel(context, strTel));
        tv.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
    }

    private static SpannableString setStrTel(Context context, final String strTel) {
        SpannableString ss = new SpannableString(strTel);
        final List<String> list = getNumbers(strTel);
        if (!StringsUtils.isEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                int finalI = i;
                ss.setSpan(new ClickableSpan() {
                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(context.getResources().getColor(R.color.colorPrimary));//设置文字颜色
                        //ds.setUnderlineText(true);//设置下划线
                    }

                    @Override
                    public void onClick(@NonNull View widget) {
                        //拨打电话
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + list.get(finalI));
                        intent.setData(data);
                        context.startActivity(intent);
                    }
                }, strTel.indexOf(list.get(i)), strTel.indexOf(list.get(i)) + 11, Spanned
                        .SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return ss;
    }

    /**
     * 从字符串中查找电话号码字符串
     */
    private static List<String> getNumbers(String content) {
        List<String> digitList = new ArrayList<>();
        Pattern p = Pattern.compile("(\\d{11})");
        Matcher m = p.matcher(content);
        while (m.find()) {
            String find = m.group(1);
            digitList.add(find);
        }
        return digitList;
    }

    public static boolean isAccessibilityEnabled(Context context) throws RuntimeException {
        if (context == null) {
            return false;
        }

        // 检查AccessibilityService是否开启
        AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
        boolean isAccessibilityEnabled_flag = am.isEnabled();

        boolean isExploreByTouchEnabled_flag = false;

        // 检查无障碍服务是否以语音播报的方式开启
        isExploreByTouchEnabled_flag = isScreenReaderActive(context);

        return (isAccessibilityEnabled_flag && isExploreByTouchEnabled_flag);

    }

    private final static String SCREEN_READER_INTENT_ACTION = "android.accessibilityservice.AccessibilityService";
    private final static String SCREEN_READER_INTENT_CATEGORY = "android.accessibilityservice.category.FEEDBACK_SPOKEN";

    private static boolean isScreenReaderActive(Context context) {

        // 通过Intent方式判断是否存在以语音播报方式提供服务的Service，还需要判断开启状态
        Intent screenReaderIntent = new Intent(SCREEN_READER_INTENT_ACTION);
        screenReaderIntent.addCategory(SCREEN_READER_INTENT_CATEGORY);
        List<ResolveInfo> screenReaders = context.getPackageManager().queryIntentServices(screenReaderIntent, 0);
        // 如果没有，返回false
        if (screenReaders == null || screenReaders.size() <= 0) {
            return false;
        }

        boolean hasActiveScreenReader = false;
        if (Build.VERSION.SDK_INT <= 15) {
            ContentResolver cr = context.getContentResolver();
            Cursor cursor = null;
            int status = 0;

            for (ResolveInfo screenReader : screenReaders) {
                cursor = cr.query(Uri.parse("content://" + screenReader.serviceInfo.packageName
                        + ".providers.StatusProvider"), null, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    status = cursor.getInt(0);
                    cursor.close();
                    // 状态1为开启状态，直接返回true即可
                    if (status == 1) {
                        return true;
                    }
                }
            }
        } else if (Build.VERSION.SDK_INT >= 26) {
            // 高版本可以直接判断服务是否处于开启状态
            for (ResolveInfo screenReader : screenReaders) {
                hasActiveScreenReader |= isAccessibilitySettingsOn(context, screenReader.serviceInfo.packageName + "/" + screenReader.serviceInfo.name);
            }

        } else {
            // 判断正在运行的Service里有没有上述存在的Service
            List<String> runningServices = new ArrayList<String>();

            android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            for (android.app.ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                runningServices.add(service.service.getPackageName());
            }

            for (ResolveInfo screenReader : screenReaders) {
                if (runningServices.contains(screenReader.serviceInfo.packageName)) {
                    hasActiveScreenReader |= true;
                }
            }
        }

        return hasActiveScreenReader;
    }

    // To check if service is enabled
    private static boolean isAccessibilitySettingsOn(Context context, String service) {

//        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
//        String settingValue = Settings.Secure.getString(
//                context.getApplicationContext().getContentResolver(),
//                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
//        if (settingValue != null) {
//            mStringColonSplitter.setString(settingValue);
//            while (mStringColonSplitter.hasNext()) {
//                String accessibilityService = mStringColonSplitter.next();
//                if (accessibilityService.equalsIgnoreCase(service)) {
//                    return true;
//                }
//            }
//        }

        return false;
    }
}
